import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    redirect: '/homepage'
  },
  {
    path: '/homepage/',
    name: 'homepage',
    component: () => import('../views/HomePage.vue')
  },

  {
    path: '/register/',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/login/',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/mineview/',
    name: 'mineview',
    component: () => import('../views/MineView.vue'),

  },
  {
    path: '/search/',
    name: 'search',
    meta:
      { keepAlive: true },

    component: () => import('../views/Search.vue')
  },
  {
    path: '/searchlist/',
    name: 'searchlist',
    component: () => import('../views/SearchList.vue')
  },
  {
    path: '/kindofview/',
    name: 'kindofview',
    component: () => import('../views/Category/KindofView.vue'),

  },
  {
    path: '/cartview/',
    name: 'cartview',
    component: () => import('../views/CartView.vue'),
    meta:{
      requireAuth:true
    }
    //  beforeEnter(to,from,next){

    //             if(!sessionStorage.getItem("username")){
    //                 next("/login?path="+to.path);
    //             }else{
    //                 next();
    //             }
    //         }
  },
  {
    path: '/detailview/:proid',
    name: 'detailview',
    component: () => import('../views/DetailView.vue')
  },
  {
    path: '/payview/',
    name: 'payview',
    component: () => import('../views/PayView.vue')
  },


]



const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局前置钩子。
router.beforeEach((to, from, next) => {
  var token = localStorage.getItem('token');

  if (to.meta.requireAuth) { // 判断跳转的路由是否需要登录
    if (token) { // vuex.state判断token是否存在
      next() // 已登录
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
  // var token = localStorage.getItem('token');
  // if( to.path == '/login' ){ //想要跳往 登录页
  //   if( token ){ //已登录
  //     next('/homepage');
  //   }else{ //未登录
  //     next();
  //   }
  // }else{ //想要跳往 其他页面
  //   if( token ){ //已登录
  //     next();
  //   }else{ //未登录
  //     next('/login');
  //   }
  // }

  // next();

});
export default router

router.beforeEach((to, from, next) => {
  // chrome兼容
  document.body.scrollTop = 0
  // firefox兼容
  document.documentElement.scrollTop = 0
  // safari兼容
  window.pageYOffset = 0
  next()
})

